<template>
  <div v-if="visible" class="iot-his-mask" @click.self="close">
    <div class="iot-his-popup">
      <div class="iot-his-header">
        <span v-if="props.hisType == 'history'">{{ $t('components.iotHis.title2') }}</span>
        <span v-else>{{ $t('components.iotHis.title') }}</span>
        
        <!-- 分页控件 -->
        <div v-if="totalPages > 1" class="iot-pagination">
        
          <button class="iot-page-btn" @click="prevPage" :disabled="currentPage <= 1">
            <i class="iconfont icon-zuobian"></i>
          </button>
          
          <template v-for="page in getPageNumbers()" :key="page">
            <button 
              v-if="page !== '...'"
              class="iot-page-number" 
              :class="{ active: page === currentPage }"
              @click="goToPage(page as number)"
              :style="{ border: page === currentPage ? '2px solid var(--theme-secondary)' : '' }"
            >
              {{ page }}
            </button>
            <span v-else class="iot-page-ellipsis">...</span>
          </template>
          
          <button class="iot-page-btn" @click="nextPage" :disabled="currentPage >= totalPages">
            <i class="iconfont icon-youbian"></i>
          </button>
        </div>
        
        <span class="iot-his-close" @click="close">×</span>
      </div>
      <div class="iot-his-table-container">
      <table class="iot-his-table">
        <thead>
          <tr>
            <th>{{ $t('components.iotHis.taskNumber') }}</th>
            <th>{{ $t('components.iotHis.scheme') }}</th>
            <th>{{ $t('components.iotHis.createTime') }}</th>
            <th v-if="props.hisType == 'history'">{{ $t('components.iotHis.executionTime') }}</th>
            <th v-if="props.hisType == 'order'">{{ $t('components.iotHis.includedProjects') }}</th>
            <th v-if="props.hisType == 'history'" >{{ $t('components.iotHis.completedProjects') }}</th>
            <th>{{ $t('components.iotHis.actions') }}</th>


          </tr>
        </thead>
        <tbody>
            <tr v-for="(item, index) in props.list" :key="item?.id || index">
              <td>{{ item?. executionNumber || '--'}}</td>
              <td>{{ item?.programmeName || '--'}}</td>
              <td>{{ item?.createTime || '--'}}</td>
              <td v-if="props.hisType == 'history'">{{ item?.executionTime || '--'}}</td>
              <td>
                <div class="image-container" >
                  <div v-for="(it, idx) in item?.items" :key="idx" class="image-item">
                  <img style="width: 36px;height: 36px;" :class="it.status ? 'success' : 'error'" :src="BaseUrl + it?.cover" alt="">
                </div>
                </div>
              </td>
              <td v-if="props.hisType == 'order'">
                <button class="dialog-confirm" @click="startTask(item)" v-if="item.status == 0">{{ $t('components.iotHis.startTask') }}</button>
                <button class="dialog-confirm" @click="startTask(item)" v-else>{{ $t('components.iotHis.goTask') }}</button>
              </td>
              <td v-if="props.hisType != 'order'">
                <button class="dialog-confirm" @click="startTask(item)" v-if="item.status == 0">{{ $t('components.iotHis.startTask') }}</button>
                <button class="dialog-confirm" @click="startTask(item)" v-if="item.status == 1">{{ $t('components.iotHis.goTask') }}</button>

                <button class="dialog-confirm" @click="switchTask(item)" v-if="item.status==2">{{ $t('components.iotHis.switchTask') }}</button>
             
              </td>
          </tr>
        </tbody>
      </table>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { computed, defineExpose, onMounted, onUnmounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { BaseUrl } from '../utils/request'
const emit = defineEmits(['switchTask', 'pageChange'])
// 使用备用翻译系统
let t = (key: any) => key
let setLang = (newLang: any) => {}

// 创建响应式的翻译函数
const translationVersion = ref(0)
const $t = (key: any) => {
  // 依赖translationVersion来触发响应式更新
  translationVersion.value
  return t(key)
}

// 初始化翻译函数
const initTranslations = async () => {
  try {
    const fallback = await import('../utils/i18n-fallback')
    t = fallback.t
    setLang = (newLang: any) => {
      fallback.setLang(newLang)
      translationVersion.value++
    }
    // 监听语言变化事件
    window.addEventListener('language-changed', () => {
      translationVersion.value++
    })
  } catch (error) {
    console.warn('Failed to load i18n fallback:', error)
  }
}
const router = useRouter()
const visible = ref(false)
const props = defineProps({
  list: {
    type: Array as any,
    default: () => []
  },
  hisType: {
    type: String,
    default: 'history'
  }
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(7)
const total = ref(0) // 从接口获取的总数
const totalPages = computed(() => Math.ceil(total.value / pageSize.value))

// 计算当前页显示的数据
const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return props.list.slice(start, end)
})

// 更新总数的方法
const updateTotal = (newTotal: number) => {
  total.value = newTotal
}

// 更新当前页码的方法
const updateCurrentPage = (page: number) => {
  console.log('IotHis updateCurrentPage:', page, '当前值:', currentPage.value)
  currentPage.value = page
  console.log('IotHis updateCurrentPage 更新后:', currentPage.value)
}

// 分页方法
const goToPage = (page: number) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
    // 通知父组件翻页
    emit('pageChange', { page, pageSize: pageSize.value })
  }
}

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
    // 通知父组件翻页
    emit('pageChange', { page: currentPage.value, pageSize: pageSize.value })
  }
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    // 通知父组件翻页
    emit('pageChange', { page: currentPage.value, pageSize: pageSize.value })
  }
}

// 获取页码数组，类似member的分页逻辑
const getPageNumbers = () => {
  const pages = []
  const maxVisible = 5
  
  console.log('getPageNumbers - currentPage:', currentPage.value, 'totalPages:', totalPages.value)
  
  if (totalPages.value <= maxVisible) {
    for (let i = 1; i <= totalPages.value; i++) {
      pages.push(i)
    }
  } else {
    if (currentPage.value <= 3) {
      for (let i = 1; i <= 4; i++) {
        pages.push(i)
      }
      pages.push('...')
      pages.push(totalPages.value)
    } else if (currentPage.value >= totalPages.value - 2) {
      pages.push(1)
      pages.push('...')
      for (let i = totalPages.value - 3; i <= totalPages.value; i++) {
        pages.push(i)
      }
    } else {
      pages.push(1)
      pages.push('...')
      for (let i = currentPage.value - 1; i <= currentPage.value + 1; i++) {
        pages.push(i)
      }
      pages.push('...')
      pages.push(totalPages.value)
    }
  }
  
  console.log('getPageNumbers 返回:', pages)
  return pages
}
const switchTask = (item: any) => {
  if (props.hisType == 'order') {
    item.resource = 0
  } else { 
    item.resource = 1
  }
  window.request?.('/task/switchTask', { method: 'POST', body: item }).then((res: any) => {
    
    emit('switchTask', item)
    
  }).then((res: any) => {
    console.log(res);
    localStorage.setItem('taskId', JSON.stringify(item))
  })
  
}


const startTask = (item: any) => {
  console.log(item);
  
  // 从items中找到status==0的项目
  const targetItem = item.items?.find((it: any) => it.status === 0)
  if (!targetItem) {
    console.warn('未找到status为0的项目')
    return
  }
  
  if (props.hisType == 'order') {
    item.resource = 0
  } else { 
    item.resource = 1
  }
  localStorage.setItem('resource', item.resource)
  window.request?.('/task/switchTask', { method: 'POST', body: item }).then((res: any) => {
    visible.value = false
    
    // 检查当前路由是否已经在bag页面
    if (router.currentRoute.value.path === '/bag') {
      // 如果已经在bag页面，发送事件通知页面重新加载数据
      console.log('发送刷新bag数据事件')
      window.dispatchEvent(new CustomEvent('refresh-bag-data', { 
        detail: { 
          targetItem: targetItem.id,
          taskData: item 
        } 
      }))
    } else {
      // 如果不在bag页面，正常跳转
      localStorage.setItem('targetItem', targetItem.id)
      router.push({
        path: '/bag',
      })
    }
    
  }).then((res: any) => {
    console.log(res);
    localStorage.setItem('taskId', JSON.stringify(item))
  })
  
}

// 重置页码的方法
const resetPage = () => {
  currentPage.value = 1
}

onMounted(async () => {
  await initTranslations()
  // 组件挂载时不立即设置，等待visible变化时设置
})

onUnmounted(() => {
  disableTableTouch()
})

// 监听visible变化，当弹窗显示时才设置触摸事件
watch(() => visible.value, (newVal) => {
  if (newVal) {
    // 弹窗显示时，延迟设置触摸事件确保DOM已渲染
    setTimeout(() => {
      enableTableTouch()
    }, 100)
  }
})

function enableTableTouch() {
  const el = document.querySelector('.iot-his-table-container') as HTMLElement
  if (!el) {
    console.log('Table container not found when setting up touch')
    return
  }
  console.log('Setting up touch events for table container')
  
  let isTouching = false
  let startY = 0
  let scrollTop = 0
  // 触摸
  el.addEventListener('touchstart', function (e) {
    console.log('Touch start')
    const te = e as TouchEvent
    if (te.touches.length !== 1) return
    isTouching = true
    startY = te.touches[0].pageY - el.offsetTop
    scrollTop = el.scrollTop
  }, { passive: true })
  el.addEventListener('touchmove', function (e) {
    if (!isTouching) return
    console.log('Touch move')
    const te = e as TouchEvent
    if (te.touches.length !== 1) return
    const y = te.touches[0].pageY - el.offsetTop
    const walkY = y - startY
    el.scrollTop = scrollTop - walkY
    te.preventDefault()
  }, { passive: false })
  el.addEventListener('touchend', function () {
    console.log('Touch end')
    isTouching = false
  })
  // 鼠标拖动
  let isDown = false
  let mouseStartY = 0
  let mouseScrollTop = 0
  el.addEventListener('mousedown', (e: MouseEvent) => {
    console.log('Mouse down')
    isDown = true
    mouseStartY = e.pageY - el.offsetTop
    mouseScrollTop = el.scrollTop
    el.classList.add('dragging')
  })
  el.addEventListener('mouseleave', () => {
    isDown = false
    el.classList.remove('dragging')
  })
  el.addEventListener('mouseup', () => {
    isDown = false
    el.classList.remove('dragging')
  })
  el.addEventListener('mousemove', (e: MouseEvent) => {
    if (!isDown) return
    console.log('Mouse move')
    e.preventDefault()
    const y = e.pageY - el.offsetTop
    const walkY = y - mouseStartY
    el.scrollTop = mouseScrollTop - walkY
  })
}

function disableTableTouch() {
  // 如需移除事件可在此实现
}

function open() { 
  visible.value = true 
  // 不在open时重置页码，让父组件控制
}
function close() { visible.value = false }
defineExpose({ open, close, updateTotal, updateCurrentPage, resetPage })
</script>
<style scoped>
.dialog-confirm {
  min-width: 90px;
  background: var(--theme-secondary);
  color: #fff;
  border: none;
  border-radius: 8px;
  font-size: 18px;
  padding: 8px 0;
  cursor: pointer;
  transition: background 0.2s;
}
.dialog-confirm:hover {
  background: #1e5e92;
}
td{
  padding: 10px;
}
.success{
  filter: brightness(0.5);
  opacity: 0.7;
}

.image-container {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  justify-content: center;
  align-items: center;
  max-width: 250px;
}

.image-item {
  flex: 0 0 auto;
}
.iot-his-mask {
  position: fixed;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0,0,0,0.08);
  z-index: 3000;
  display: flex;
  align-items: flex-end;
  justify-content: center;
}
.iot-his-popup {
  width: 98vw;
  max-width: 1500px;
  background: #fff;
  border-radius: 18px 18px 0 0;
  box-shadow: 0 -2px 16px rgba(30,94,146,0.10);
  padding: 28px 32px 32px 32px;
  margin-bottom: 0;
  animation: popupUp 0.3s cubic-bezier(.77,0,.18,1);
  min-height: 60vh;
  max-height:60vh;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}
@keyframes popupUp {
  from { transform: translateY(100%); }
  to { transform: translateY(0); }
}
.iot-his-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 22px;
  font-weight: bold;
  color: #222;
  margin-bottom: 18px;
}
.iot-his-close {
  font-size: 32px;
  color: #888;
  cursor: pointer;
  margin-left: 18px;
  font-weight: normal;
  transition: color 0.2s;
}
.iot-his-close:hover {
  color: #158ac0;
}
.iot-his-table-container {
  overflow-y: auto;
  max-height: 50vh;
  scrollbar-width: thin;
  scrollbar-color: rgba(0,0,0,0.2) transparent;
  -webkit-overflow-scrolling: touch;
}
.iot-his-table-container::-webkit-scrollbar {
  width: 4px;
  height: 4px;
}
.iot-his-table-container::-webkit-scrollbar-track {
  background: transparent;
}
.iot-his-table-container::-webkit-scrollbar-thumb {
  background-color: rgba(0,0,0,0.2);
  border-radius: 2px;
}
.iot-his-table {
  width: 100%;
  border-collapse: collapse;
  background: transparent;
  font-size: 18px;
  border: 1.5px solid #d0d0d0;
  table-layout: fixed;
}
.iot-his-table th, .iot-his-table td {
  border: 1.5px solid #d0d0d0;
}
.iot-his-table th {
  color: #888;
  font-weight: 500;
  background: #f5fafd;
  padding: 12px 0;
}
.iot-his-table td {
  background: #fff;
  text-align: center;
  padding: 5px 0;
  color: #333;
}
.iot-his-icon {
  width: 36px;
  height: 36px;
  border-radius: 8px;
  object-fit: cover;
}

/* 分页样式 */
.iot-pagination {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-right: 20px;
}

.iot-page-btn {
  background: var(--theme-secondary);
  color: #fff;
  border: none;
  border-radius: 50%;
  width: 32px;
  height: 32px;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background 0.2s;
}

.iot-page-btn:hover:not(:disabled) {
  background: #1e5e92;
}

.iot-page-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.iot-page-number {
  background: #fff;
  color: #333;
  border: 1px solid #d0d0d0;
  border-radius: 50%;
  width: 32px;
  height: 32px;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.iot-page-number:hover {
  background: var(--theme-secondary);
  color: #fff;
  border-color: var(--theme-secondary);
}

.iot-page-number.active {
  background: var(--theme-secondary) !important;
  color: #fff !important;
  border-color: var(--theme-secondary) !important;
}

.iot-page-ellipsis {
  color: #888;
  font-size: 14px;
  margin: 0 4px;
}
</style>
